package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type JsonResult struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

func Json(code int, message string, data interface{}) *JsonResult {
	return &JsonResult{
		Code:    code,
		Message: message,
		Data:    data,
	}
}

func JsonData(data interface{}) *JsonResult {
	return &JsonResult{
		Code:    200,
		Data:    data,
		Message: "请求成功",
	}
}

func JsonSuccess() *JsonResult {
	return &JsonResult{
		Code:    200,
		Data:    nil,
		Message: "请求成功",
	}
}

func JsonError(err *ErrorCode) *JsonResult {
	return &JsonResult{
		Code:    err.Code,
		Message: err.Message,
	}
}

func (json *JsonResult) JsonWithMsg(message string) *JsonResult {
	json.Message = message
	return json
}

func (json *JsonResult) JsonWithCode(code int) *JsonResult {
	json.Code = code
	return json
}

func (json *JsonResult) JsonWithData(data interface{}) *JsonResult {
	json.Data = data
	return json
}

func JSON(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, data)
	c.Abort()
}

func FailedParam(c *gin.Context, err *ErrorCode) {
	result := JsonResult{
		Code:    err.Code,
		Message: err.Message,
	}
	c.JSON(http.StatusOK, result)
	c.Abort()
}
